package sunyu.kit.solr;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.slf4j.Logger;
import sunyu.kit.common.ExceptionKit;
import sunyu.kit.common.JsonKit;
import sunyu.kit.common.LogKit;
import sunyu.kit.common.StringKit;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Solr工具类
 *
 * @author 孙宇
 */
public class SolrKit {

    private static final Logger logger = LogKit.getLogger();

    private static final Map<String, SolrClient> solrClientPool = new ConcurrentHashMap<>();//solr客户端连接池

    /**
     * 系统关闭前调用此方法
     */
    public static void destroy() {
        logger.info("销毁solr客户端开始");
        for (Map.Entry<String, SolrClient> entry : solrClientPool.entrySet()) {
            try {
                entry.getValue().close();
            } catch (IOException e) {
                logger.error(ExceptionKit.getStackTrace(e));
            }
        }
        logger.info("销毁solr客户端结束");
    }

    /**
     * 添加一个客户端
     *
     * @param name    客户端名称
     * @param solrUrl 地址，必须符合JSON格式(支持单机和集群)：
     *                <p>
     *                {coreName:'core1',url:'http://localhost:8081/solr/'}，而且url属性最后一个字符必须是"/"
     *                <p>
     *                {coreName:'core1',zookeeperHosts:'10.44.138.70:2191,10.44.200.1:2191,10.25.133.247:2191'}
     */
    public static void addClient(String name,
                                 String solrUrl) {
        logger.info("添加一个solr客户端 {} 开始", name);
        logger.info(solrUrl);
        if (solrClientPool.containsKey(name)) {
            logger.error("solr客户端 {} 已存在！", name);
        } else {
            Map<String, String> urlMap = JsonKit.toObject(solrUrl, Map.class);
            String coreName = urlMap.get("coreName");
            if (StringKit.isBlank(coreName)) {
                logger.error("缺少coreName配置项！");
                return;
            }
            String url = urlMap.get("url");//url最后一个字符必须是"/"
            String zookeeperHosts = urlMap.get("zookeeperHosts");
            if (StringKit.isBlank(url) && StringKit.isBlank(zookeeperHosts)) {
                logger.error("缺少url或zookeeperHosts配置项！");
                return;
            }
            if (StringKit.isNotBlank(url) && StringKit.isNotBlank(zookeeperHosts)) {
                logger.error("配置项参数不正确！");
                return;
            }
            if (StringKit.isNotBlank(url)) {
                SolrClient client = new HttpSolrClient.Builder(url + coreName).build();
                solrClientPool.put(name, client);
            }
            if (StringKit.isNotBlank(zookeeperHosts)) {
                CloudSolrClient client = new CloudSolrClient.Builder().withZkHost(zookeeperHosts).build();
                client.setDefaultCollection(coreName);
                solrClientPool.put(name, client);
            }
        }
        logger.info("添加一个solr客户端 {} 结束", name);
    }

    /**
     * 获得一个solr客户端
     *
     * @param name 客户端名称
     * @return
     */
    public static SolrClient getClient(String name) {
        return solrClientPool.get(name);
    }

}
